"""
题目：移除双链表的最后一个节点，返回原头节点（空链表返回 None）。
"""


class Node:
    def __init__(self, val=0, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next


def delete_tail(head):
    """删除双链表的尾节点"""
    if head is None:
        return None  # 空链表
    if head.next is None:
        return None  # 单节点链表，删除后为空
    # 找到尾节点的前驱
    current = head
    while current.next.next:  # 循环结束时current是尾节点的前驱
        current = current.next
    #让尾节点断掉 即断开和尾节点的关联
    current.next = None
    return head


def create_doubly_linked_list(arr):
    if not arr:
        return None
    head = Node(arr[0])
    current = head
    for val in arr[1:]:
        new_node = Node(val)
        current.next = new_node
        new_node.prev = current
        current = new_node
    return head


def traverse(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result


# 测试
if __name__ == "__main__":
    head = create_doubly_linked_list([1, 2, 3, 4])
    new_head = delete_tail(head)
    print(traverse(new_head))  # 输出: [1, 2, 3]

    two_node_head = create_doubly_linked_list([5, 6])
    new_two_head = delete_tail(two_node_head)
    print(traverse(new_two_head))  # 输出: [5]